package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.UserService;

@Controller
public class UserController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;

	@Autowired
	private UserService userService;

	@RequestMapping("/secure/showAddUser.do")
	public String showAddUser(Model model) {
		model.addAttribute("user", new User());
		return "editUser";
	}

	@RequestMapping("/secure/showEditUser.do")
	public String showEditUser(@RequestParam Integer id, Model model) {
		model.addAttribute("user", userService.findById(id));
		return "editUser";
	}

	@RequestMapping("/secure/saveUser.do")
	public String SaveUser(@ModelAttribute("user") User user, BindingResult result, Model model, HttpServletRequest request) {
		try {
			user = userService.saveUser(user, getUserId(request));
			saveMessage(request, getText("editUser.message.success"));
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		model.addAttribute("user", user);
		return "editUser";
	}

	@RequestMapping("/secure/showUserList.do")
	public String showUserList(Model model) {
		model.addAttribute("users", userService.findAll());
		return "userList";
	}
}
